<template>
  <div v-if="pageData.totalPage > 1">
    <span>共{{pageData.totalPage}}页</span>

    <span class="page_item" v-if="pageData.currentPage !== 1" @click="lastPage()">上一页</span>
    
    <span class="page_item_interval"  v-for="(page,index) in pageList" :key="index" >
        <span v-if="page !== -1" :ref="'p'+page" class="page_item" @click="movePage(page)">{{page}}</span>
        <span v-else>...</span>
    </span>
    <span class="page_item" v-if="pageData.currentPage !== pageData.totalPage" @click="nextPage()">下一页</span>
  </div>
</template>

<script>
export default {
  components: {
    
  },
  mounted() {
    
  },
  computed:{
    pageList() {
        let _p = this.pageData.currentPage;
        let _t = this.pageData.totalPage;
        // console.log('当前页',_p,'总共',_t)
        let arr = [];
        arr.push(1)
        if(_p<=4){
            for(let i = 2; i <= _p; i++){
                arr.push(i);
            }
        }else{
            arr.push(-1)
            for(let i = _p -2; i <= _p; i++){
                arr.push(i);
            }
        }
        if(_t - _p <= 3 ){
            for(let i = _p+1; i<_t; i++){
                arr.push(i)
            }
        }else{
            for(let i = _p+1; i<= _p+2; i++){
                arr.push(i)
            }
            arr.push(-1)
        }
        if(_t != _p){
            arr.push(_t);
        }
        return arr;
    }
  },
  watch:{
      pageList:{
          handler: function(){
                
                this.$nextTick(() => { 
                    // console.log("watch：pageList修改了", this.currentPage,this.$refs['p'+this.currentPage][0])
                    if(this.pageData.totalPage > 1){
                        this.$refs['p'+this.currentPage][0].style.color = '#00a1d6'
                    }
                });
          },
          immediate: true
      }
  },
  props:{
      pageData: Object,
  },
  data() {
    return {
    //   pageData:{
    //       currentPage:1,
    //       totalPage:5,
    //   },
      currentPage: this.pageData.currentPage,
    }
  },
  methods: {
    // 上一页
    lastPage(){
        this.itemDefaultColor()
        this.currentPage = this.pageData.currentPage-1;
        this.emitEvent()
    },
    // 指定页
    movePage(move){
        if(move !== this.pageData.currentPage){
            this.itemDefaultColor()
            this.currentPage = move;
            this.emitEvent()
        }
    },
    // 下一页
    nextPage(){
        this.itemDefaultColor()
        this.currentPage = this.pageData.currentPage+1;
        this.emitEvent()
    },
    // 选中其他页时，将当前页修改为默认色
    itemDefaultColor(){
        this.$refs['p'+this.currentPage][0].style.color = '#000'
    },
    // 修改页码
    emitEvent(){
        console.log("page：页码变为", this.currentPage)
        this.$emit("pageChangeEvent", this.currentPage);
    }
  },
}
</script>

<style>
.page_item{
    cursor: pointer;
    color: #000;
}
.page_item_interval{
    margin: 0 3px;
}
</style>